import axios, { AxiosRequestHeaders, AxiosResponse } from 'axios'

// 创建一个 axios 实例
const http = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL as string, // 所有的请求地址前缀部分
    timeout: 60000, // 请求超时时间毫秒
    withCredentials: true, // 异步请求携带cookie
})

// 添加请求拦截器
http.interceptors.request.use(
    function (config) {
        return config
    },
    function (error) {
        console.log(error)
        return Promise.reject(error)
    }
)

// 添加响应拦截器
http.interceptors.response.use(
    function (response) {
        console.log("响应数据", response)
        return response
    },
    function (error) {
        console.log(error)
        return Promise.reject(error)
    }
)

export class ResponseDto {
    code: number
    msg: string
    private _data: any

    constructor(code: number, msg: string) {
        this.code = code
        this.msg = msg
    }

    set data(data: any) {
        this._data = data
    }
    get data() {
        return this._data
    }
}


export interface IResponse {
    error?: Error;
    resp?: ResponseDto;
}


export const httpGet = function (url: string, params?: object, headers?: AxiosRequestHeaders): Promise<AxiosResponse<ResponseDto>> {
    return http.request({ url, method: "GET", params, headers: headers ?? { 'Accept': 'text/plain, */*' } })
}


export const httpPost = function (url: string, data?: object, headers?: AxiosRequestHeaders): Promise<AxiosResponse<ResponseDto>> {
    return http.request({ url, method: "POST", headers: headers ?? { 'Accept': 'application/json, text/plain, */*' }, data })
}


/**
 * 统一处理Promise结果对象，将返回值封装为一个对象，error属性为错误，resp属性为返回的数据
 *
 * @param {Promise<AxiosResponse<ResponseDto>>} promise 对象
 * @returns {error: "", resp: {}}
 */
export const to = function (promise: Promise<AxiosResponse<ResponseDto>>): Promise<IResponse> {
    return promise
        .then((axiosResp: AxiosResponse<ResponseDto>) => {
            const res: IResponse = {
                error: undefined,
                resp: axiosResp.data,
            }
            return res
        })
        .catch(err => {
            const res: IResponse = {
                error: new Error(err),
                resp: undefined,
            }
            return res
        })
}


export default http